package home.action;

import home.model.Goods;
import home.model.Skill;
import home.model.Users;
import home.service.GoodsService;
import home.service.UsersService;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class GoodsAction extends ActionSupport{
	private GoodsService goodss;
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}

	private UsersService userss;
	private String type;
	private int id;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public UsersService getUserss() {
		return userss;
	}
	public void setUserss(UsersService userss) {
		this.userss = userss;
	}
	public GoodsService getGoodss() {
		return goodss;
	}
	public void setGoodss(GoodsService goodss) {
		this.goodss = goodss;
	}
	public String execute() throws Exception{
		return SUCCESS;
	}
	
	public String goodsRemove() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		
		Users users = (Users) session.getAttribute("users");
		if(type.equals("goodsUse")){			
			Goods goods = users.getGoodsUse().remove(id);
			users.getGoodsItem().add(goods);
		}else if(type.equals("goodsItem")){
			Goods goods = users.getGoodsItem().remove(id);
			for(int i = 0;i<users.getGoodsUse().size();i++){
				if( users.getGoodsUse().get(i).getType().equals(goods.getType()) )
					return SUCCESS;
			}
			users.getGoodsUse().add(goods);
		}else if(type.equals("skillUse")){
			Skill skill = users.getSkillUse().remove(id);
			users.getSkillItem().add(skill);
		}else{
			int num = (int) users.getSkillItem().get(id).getPossible();
			if(users.getSkillUse() != null){
				for(int i = 0;i<users.getSkillUse().size();i++){
					num = num + (int) users.getSkillUse().get(i).getPossible();
				}
			}
			Skill skill;
			if(num>100) return SUCCESS;
			else skill = users.getSkillItem().remove(id);
			
			users.getSkillUse().add(skill);
		}
		
	    userss.saveUsers(users);
	    session.setAttribute("users", users);
		return SUCCESS;
	}
}
